package com.shenfc.fxzj.shiro;

import com.shenfc.fxzj.constants.CodeConstants;
import com.shenfc.fxzj.domain.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import com.shenfc.fxzj.service.ISysUserService;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import static com.shenfc.fxzj.constants.CodeConstants.SESSION_USER;

/**
 * Created by Administrator on 2018/2/5 0005.
 */
public class RememberMeFilter extends FormAuthenticationFilter {


    @Autowired
    private ISysUserService sysUserService;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated() && subject.isRemembered() && subject.getSession().getAttribute(CodeConstants.SESSION_USER) == null) {
            Object principal = subject.getPrincipal();
            if (principal != null) {
                String userName = (String) principal;
                SysUser sysUser = sysUserService.getSysUserByUserName(userName);
                subject.getSession().setAttribute(SESSION_USER, sysUser);
            }
        }
        return subject.isAuthenticated() || subject.isRemembered();
    }
}
